import requests
import time
import random
import threading

BASE_URL = "http://localhost:5000"
ENDPOINTS = [
    "/api/users",
    "/api/orders",
    "/api/products",
    "/api/chain-call"
]


def generate_traffic():
    """生成测试流量"""
    for i in range(20):
        endpoint = random.choice(ENDPOINTS)
        try:
            if endpoint == "/api/performance":
                response = requests.get(f"{BASE_URL}{endpoint}?delay={random.uniform(0.1, 1)}")
            elif endpoint == "/api/error-test":
                error_type = random.choice(['not_found', 'server_error', 'validation'])
                response = requests.get(f"{BASE_URL}{endpoint}?type={error_type}")
            else:
                response = requests.get(f"{BASE_URL}{endpoint}")

            print(f"Request to {endpoint}: Status {response.status_code}")
        except Exception as e:
            print(f"Error requesting {endpoint}: {e}")

        time.sleep(random.uniform(0.5, 2))


if __name__ == "__main__":
    print("开始生成测试流量...")
    threads = []
    for i in range(5):  # 启动3个线程同时生成流量
        thread = threading.Thread(target=generate_traffic)
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

    print("测试流量生成完成！")